const express = require("express");

let menuList = require("../data/menuData.json");
const roleMenu = require("../data/roleMenu.json");
const menuControl = express.Router();

// 获取所有菜单列表
menuControl.get("/", function (req, res) {
  //   console.log(req.query);
  const resMenuList = getMenuList(menuList);
  return res.send({
    code: 200,
    message: "成功",
    data: resMenuList,
    ok: true,
  });
});
// 新增菜单
menuControl.post("/save", function (req, res) {
  let id = menuList.slice(-1)[0].id + 1;
  menuList.push({
    id,
    ...req.body,
    createTime: new Date().toLocaleString(),
    updateTime: new Date().toLocaleString(),
  });
  return res.send({
    code: 200,
    message: "成功",
    data: {},
    ok: true,
  });
});
// 修改菜单
menuControl.put("/update", function (req, res) {
  const menu = menuList.find((m) => m.id == Number(req.body.id));
  if (menu && !menu.del) {
    menu.name = req.body.name;
    menu.code = req.body.code;
    menu.updateTime = new Date().toLocaleString();
    return res.send({
      code: 200,
      message: "成功",
      data: {},
      ok: true,
    });
  } else {
    return res.send({
      code: 201,
      message: "未找到该角色",
      data: {},
      ok: true,
    });
  }
});
// 删除菜单
menuControl.delete("/remove", function (req, res) {
  console.log(req.query);
  // 根据id搜索菜单
  // 若关联角色，删除失败，要先解除关联
  let flag = false;
  roleMenu.forEach((item) => {
    if (item.menuId.includes(Number(req.query.id))) {
      flag = true;
    }
  });
  if (flag)
    return res.send({
      code: 201,
      message: "存在关联角色，删除失败",
      data: {},
      ok: true,
    });
  // 若没有关联角色 直接删除
  let menu = menuList.find((item) => item.id == req.query.id);
  menu.del = true;
  return res.send({
    code: 200,
    message: "成功",
    data: {},
    ok: true,
  });
});

module.exports = menuControl;

// 获取所有菜单 过滤del标志
const getMenuList = (list) => {
  let lv1 = [],
    lv2 = [],
    lv3 = [],
    lv4 = [];

  list.forEach((item) => {
    if (!item.del) {
      switch (item.level) {
        case 1:
          lv1.push(item);
          break;
        case 2:
          lv2.push(item);
          break;
        case 3:
          lv3.push(item);
          break;
        case 4:
          lv4.push(item);
          break;
        default:
          break;
      }
    }
  });
  lv3.forEach((item) => {
    let children = lv4.filter((m) => m.pid === item.id);
    item.children = children;
  });
  lv2.forEach((item) => {
    let children = lv3.filter((m) => m.pid === item.id);
    item.children = children;
  });
  lv1.forEach((item) => {
    let children = lv2.filter((m) => m.pid === item.id);
    item.children = children;
  });

  return lv1;
};
